package com.nari.ncps.screen.service.impl.ne;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.ne.NeOpermonEqpState;
import com.nari.ncps.screen.mapper.ne.NeOpermonWindStateMapper;
import com.nari.ncps.screen.service.ne.NeOpermonWindStateService;
import com.nari.ncps.screen.vo.ne.NeWindEquipmentStatusVO;
import com.nari.ncps.screen.entity.ne.NeOpermonWindState;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

/**
 * <p>
 * 风电设备状态监测表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeOpermonWindStateServiceImpl extends ServiceImpl<NeOpermonWindStateMapper, NeOpermonWindState> implements NeOpermonWindStateService {

    @Override
    public NeWindEquipmentStatusVO getWindEquipmentStatus(Integer year) {
        // 如果没有指定年份，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 查询指定年份的最新数据
        LambdaQueryWrapper<NeOpermonWindState> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NeOpermonWindState::getOrgCode, "100360");
        queryWrapper.eq(NeOpermonWindState::getDelFlag, 0);
//        queryWrapper.orderByDesc(NeOpermonWindState::getMonth);
        queryWrapper.last("LIMIT 1");
        
        NeOpermonWindState entity = this.getOne(queryWrapper);
        
        // 构建返回VO
        NeWindEquipmentStatusVO vo = new NeWindEquipmentStatusVO();
        if (entity != null) {
            vo.setNormalCount(entity.getNormalCount());
            vo.setStandbyCount(entity.getStandbyCount());
            vo.setFaultCount(entity.getFaultCount());
            vo.setCommFailureCount(entity.getCommFailureCount());
            vo.setUnknownStatusCount(entity.getUnknownStatusCount());
            
            // 计算其他数量 = 总数 - 已统计的各类数量
            Integer total = entity.getTotalTurbines();
            if (total != null) {
                int counted = (entity.getNormalCount() != null ? entity.getNormalCount() : 0)
                        + (entity.getStandbyCount() != null ? entity.getStandbyCount() : 0)
                        + (entity.getFaultCount() != null ? entity.getFaultCount() : 0)
                        + (entity.getCommFailureCount() != null ? entity.getCommFailureCount() : 0)
                        + (entity.getUnknownStatusCount() != null ? entity.getUnknownStatusCount() : 0);
                vo.setOther(total - counted);
            }
        }else{
            vo.setNormalCount(0);
            vo.setStandbyCount(0);
            vo.setFaultCount(0);
            vo.setCommFailureCount(0);
            vo.setUnknownStatusCount(0);
            vo.setOther(0);
        }
        
        return vo;
    }

}
